<template>
  <div>
    <el-card>
      <el-page-header icon="" title="用户管理">
        <template #content>
          <span class="text-large font-600 mr-3">用户列表</span>
        </template>
      </el-page-header>

      <el-from>
        <el-row :gutter="30" style="margin-top: 20px">
          <el-col :span="7">
            <el-form-item label="工号">
              <el-input v-model.number="query.username" type="number" clearable />
            </el-form-item>
          </el-col>
          <el-button type="primary" @click="handleSerch()">搜索</el-button>
        </el-row>
      </el-from>

      <el-table :data="tableData" style="width: 100%" stripe v-loading="loading">
        <el-table-column prop="username" label="工号" width="120" />
        <el-table-column label="头像">
          <template #default="scope">
            <div v-if="scope.row.avatar">
              <el-avatar :size="50" :src="'http://localhost:3000' + scope.row.avatar" />
            </div>
            <div v-else>
              <el-avatar :size="50" :src="'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column label="性别">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <el-tag class="ml-2" type="danger" v-if="scope.row.role === 1">管理员</el-tag>
            <el-tag class="ml-2" type="success" v-else>教师</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="default" @click="handleEdit(scope.row)" :icon="Edit" circle></el-button>
            <el-popconfirm title="你确定要删除吗？" confirm-button-text="确定" cancel-button-text="取消" width="200" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button size="default" type="danger" :icon="Delete" circle></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="query.page" v-model:page-size="query.limit" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="totalUser" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑用户" width="50%">
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="80px" class="demo-ruleForm" status-icon>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工号" prop="username">
              <el-input v-model="userForm.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" class="m-2" placeholder="Select" style="width: 100%">
                <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" class="m-2" placeholder="Select" style="width: 100%">
                <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const loading = ref(true)
const dialogVisible = ref(false)
const tableData = ref([])
const userFormRef = ref()
const userForm = reactive({
  username: null,
  password: '',
  name: '',
  gender: null,
  role: null,
  phone: null,
  email: ''
})
const userFormRules = reactive({
  username: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
})
const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]
const roleOptions = [
  { label: '管理员', value: 1 },
  { label: '教师', value: 2 }
]
let totalUser = 0
const query = reactive({
  page: 1,
  limit: 5,
  username: null
})

onMounted(() => {
  getTableData()
})
const getTableData = async () => {
  const res = await axios.get('/api/user/list', {
    params: query
  })
  tableData.value = res.data.data

  const restotal = await axios.get('/api/user/total', {
    params: {
      username: query.username
    }
  })
  totalUser = restotal.data.data
  loading.value = false
}
const handleDelete = async (data) => {
  await axios.delete(`/api/user/list/${data._id}`)
  if (data.role === 2) {
    await axios.delete(`/api/teacher/list/${data.username}`)
  }
  getTableData()
  ElMessage.success('删除成功！')
}
const handleEdit = async (data) => {
  const res = await axios.get(`/api/user/list/${data._id}`)
  // console.log(res.data)
  Object.assign(userForm, res.data.data[0])
  dialogVisible.value = true
}
const handleEditConfirm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      await axios.put(`/api/user/list/${userForm._id}`, userForm)
      getTableData()
      ElMessage.success('编辑成功！')
      dialogVisible.value = false
    }
  })
}
const handleSizeChange = (val) => {
  query.limit = val
  getTableData()
}
const handleCurrentChange = (val) => {
  getTableData()
}
const handleSerch = () => {
  loading.value = true
  getTableData()
  // 解决pagination视图不更新...
  nextTick(async () => {
    const restotal = await axios.get('/api/user/total', {
      params: {
        username: query.username
      }
    })
    totalUser = restotal.data.data
    loading.value = false
  })
}
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 30px;
}
</style>
